package handler

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"gitee.com/DonHz/cloud-file-storage/db"
	"gitee.com/DonHz/cloud-file-storage/util"
	"github.com/gin-gonic/gin"
	"time"
)

// SignUpHandler 处理用户注册请求
func SignUpHandler(c *gin.Context) {
	type SignUpReq struct {
		Phone          string `json:"phone"`
		Password       string `json:"password"`
		UserName       string `json:"username"`
		RepeatPassword string `json:"passwordc"`
	}
	var req SignUpReq
	if err := c.ShouldBindJSON(&req); err != nil {
		fmt.Println(err)
		c.JSON(400, gin.H{
			"msg": "参数错误",
		})
		return
	}
	// 校验参数
	if len(req.Phone) != 11 {
		c.JSON(400, gin.H{
			"msg": "手机号长度错误",
		})
		return
	}
	if len(req.Password) < 6 {
		c.JSON(400, gin.H{
			"msg": "密码长度错误",
		})
		return
	}
	if len(req.UserName) < 3 || len(req.UserName) > 16 {
		c.JSON(400, gin.H{
			"msg": "用户名长度错误",
		})
		return
	}
	// 对密码进行加密
	hash := md5.Sum([]byte(req.Password))
	hashedPassword := hex.EncodeToString(hash[:])
	// 保存用户信息
	err := db.SignUp(req.Phone, hashedPassword, req.UserName)
	if err != nil {
		fmt.Println(err)
		c.JSON(500, gin.H{
			"msg": "注册失败",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "注册成功",
	})
}

func SignInHandler(c *gin.Context) {
	type SignInReq struct {
		UserName string `json:"username"`
		Password string `json:"password"`
	}
	var req SignInReq
	// 解析请求参数
	if err := c.ShouldBindJSON(&req); err != nil {
		fmt.Println("参数错误：", err)
		c.JSON(400, gin.H{
			"msg": "参数错误",
		})
		return
	}
	// 校验参数
	phone := req.UserName
	user, err := db.SignIn(phone, req.Password)
	if err != nil {
		fmt.Println(err)
		c.JSON(500, gin.H{
			"msg": "手机号或密码错误",
		})
		return
	}
	//生成token
	token := GenToken(phone)
	res, err := db.UpdateToken(user.Phone, token)
	body := struct {
		Id       int64  `json:"id"`
		UserName string `json:"Username"`
		Token    string `json:"Token"`
	}{
		Id:       res.Id,
		UserName: res.Phone,
		Token:    token,
	}
	if err != nil {
		fmt.Println("更新token失败: ", err)
		panic(err)
	}
	c.Set("token", token)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"data": body,
	})
}

func UserInfoHandler(c *gin.Context) {
	//校验token
	req := struct {
		Phone string `json:"username"`
		Token string `json:"token"`
	}{
		Phone: c.Query("username"),
		Token: c.Query("token"),
	}
	fmt.Println(req)
	// 查询用户信息
	user, err := db.GetUserInfo(req.Phone)
	if err != nil {
		fmt.Println(err)
		c.JSON(500, gin.H{
			"msg": "系统错误",
		})
		return
	}
	resp := util.RespMsg{
		Code: 200,
		Msg:  "查询成功",
		Data: struct {
			UserName string `json:"username"`
			CreateAt string `json:"SignupAt"`
		}{
			UserName: user.Phone,
			CreateAt: time.Unix(user.CreateAt, 0).Format("2006-01-02 15:04:05"),
		},
	}
	c.JSON(200, resp)
}

func GenToken(phone string) string {
	//md5(phone+timestamp+token_salt)+timestamp[:8]
	timestamp := fmt.Sprintf("%d", time.Now().Unix())
	tokenPrefix := md5.Sum([]byte(phone + timestamp + "token_salt"))
	return hex.EncodeToString(tokenPrefix[:]) + timestamp[:8]
}
